package com.ele.server;

import com.ele.server.util.ImageWriter;
import com.ele.shared.AttachmentException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ImageUploadServlet extends HttpServlet {

	private String fileUploadPath = "c:/sandbox/sele";

	private int maxLargeImageSize = 600;
	private int maxThumbImageSize = 140;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			if (ServletFileUpload.isMultipartContent(req)) {
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload fileupload = new ServletFileUpload(factory);

				List items = fileupload.parseRequest(req);

				for (Object item1 : items) {
					FileItem item = (FileItem) item1;
					String fieldValue = item.getName();

					if (!item.isFormField()) {
						String fieldName = item.getFieldName();

						if (fieldName.equals("ImageMain") && isValidContentType(fieldValue)) {
							String fileExtension = extractExtension(fieldValue);
							BufferedImage image = readImage(item);

							ImageWriter imageWriter = new ImageWriter(image, fileExtension, fileUploadPath);
							imageWriter.write("original");
							imageWriter.write("default", maxLargeImageSize);
							imageWriter.write("thumb", maxThumbImageSize);
						}
					}
				}
			}
		} catch (AttachmentException e) {
			e.printStackTrace();
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

	private BufferedImage readImage(FileItem item) throws AttachmentException {
		BufferedInputStream bis = null;
		try {
			bis = new BufferedInputStream(item.getInputStream());
			return ImageIO.read(bis);
		} catch (Exception e) {
			throw new AttachmentException("Failure on image reading", e);
		} finally {
			if (bis != null) try {
				bis.close();
			} catch (IOException logOrIgnore) { }
		}
	}

	private boolean isValidContentType(String fieldValue) {
		File file = new File(fieldValue);
		String filename = file.getName();
		String type = getServletContext().getMimeType(filename);
		return type != null && type.startsWith("image");
	}

	private String extractExtension(String filename) {
		String lower = filename.toLowerCase();
		return lower.substring(lower.indexOf("") + 1, lower.length());
	}
}
